﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Happy.ExtentionMethods;

namespace Happy.Web.Mvc
{
    /// <summary>
    /// 将服务器端的资源文件转换为Javascript代码，主要为了在服务端和客户端之间共享资源文件。
    /// </summary>
    public sealed class JavascriptResourceResult : JavaScriptResult
    {
        /// <summary>
        /// 构造方法。
        /// </summary>
        public JavascriptResourceResult(string javascriptObjectName, Type resourceType)
        {
            javascriptObjectName.MustNotNullAndNotWhiteSpace("javascriptObjectName");
            resourceType.MustNotNull("resourceType");

            var namespaceDefinitionString = GetNamespaceDefinitionString(javascriptObjectName);
            var keyValueStrings = GetKeyValueString(resourceType);

            this.Script = string.Format("{0};{1} = {{{2}}}", namespaceDefinitionString, javascriptObjectName, keyValueStrings);
        }

        private static string GetNamespaceDefinitionString(string javascriptObjectName)
        {
            var names = javascriptObjectName.Split('.');

            var namespaces = names.Take(names.Length - 1).Select((x, index) =>
            {
                return string.Join(".", names.Take(index + 1).ToArray());
            });

            var sb = new StringBuilder();
            sb.AppendFormat("var {0} = {0} || {{}}", namespaces.First());
            foreach (var item in namespaces.Skip(1))
            {
                sb.AppendFormat("{0} = {0} || {{}}", item);
            }

            return sb.ToString();
        }

        private static string GetKeyValueString(Type resourceType)
        {
            var keyvalues = resourceType
                .GetProperties()
                .Select(x =>
                {
                    return string.Format("{0}: '{1}'", x.Name, x.GetValue(null));
                }).ToArray();

            return string.Join(",", keyvalues);
        }
    }
}
